package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.dto.ResponseDto;
import com.cyzy.mapper.UserMapper;
import com.cyzy.pojo.Driver;
import com.cyzy.pojo.Passenger;
import com.cyzy.service.UserService;
import com.cyzy.util.VerificationCodeUtil;
import com.cyzy.utils.HashUtil;
import com.cyzy.utils.JwtUtil;
import com.cyzy.utils.RedisUtil;
import jakarta.servlet.http.HttpSession;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Passenger> implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;



    @Override
    public Map<String,Object> login(String acc, String password) {
        //根据账号或手机号查找用户并且用户的状态为0 （0：正常  1：禁用  2：删除）
        LambdaQueryWrapper<Passenger> wrapper=new LambdaQueryWrapper<>();
        wrapper.and(queryWrapper -> queryWrapper
                .eq(Passenger::getUserAcc,acc)
                .or()
                .eq(Passenger::getPhone,acc)
                )
                .eq(Passenger::getUserStatus,0);
        Passenger passenger = userMapper.selectOne(wrapper);
        if(passenger == null){
            return null;
        }
        //校验密码
        if(!HashUtil.checkPassword(password,passenger.getPassword())){
            return null;
        }
        //生成token
        Map<String,Object> map=new HashMap<>();
        map.put("id",passenger.getUserId());
        map.put("acc",passenger.getUserAcc());
        String token = JwtUtil.genToken(map);
        //存储token到redis
        redisUtil.set(token,token);
        redisUtil.setExpire(token,3600);
        //返回结果集给controller
        Map<String,Object> result=new HashMap<>();
        result.put("user",passenger);
        result.put("token",token);
        return result;
    }

    @Override
    public ResponseDto register(Passenger user) {
        //根据账号或手机号查找用户
        LambdaQueryWrapper<Passenger> wrapper=new LambdaQueryWrapper<Passenger>()
                .eq(Passenger::getUserAcc,user.getUserAcc())
                .or()
                .eq(Passenger::getPhone,user.getPhone());
        Passenger passenger = this.getOne(wrapper);
        if(passenger!=null){
            return ResponseDto.fail("该用户已存在！");
        }
        //密码加密
        user.setPassword(HashUtil.hashPassword(user.getPassword()));
        int i=userMapper.insert(user);
        if(i<=0){
            return ResponseDto.fail("注册失败！");
        }
        return ResponseDto.ok("注册成功！");
    }

    @Override
    public String getPhoneCode(String phone) throws Exception {
        // 1. 验证手机号格式
        if (!isValidPhoneNumber(phone)) {
            return "无效的手机号格式";
        }

        // 2. 检查发送频率
        if (isRateLimited(phone)) {
            return "发送太频繁，请稍后再试";
        }

        //2.1 检查手机号是否在乘客表表中存在
        LambdaQueryWrapper<Passenger> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Passenger::getPhone,phone);
        Passenger passenger = userMapper.selectOne(wrapper);
        if( passenger == null){
            return  "用户不存在！";
        }
        // 3. 生成验证码
        String code = VerificationCodeUtil.generateCode();


        //存入map中
        Map<String,Object> bodyMap = new HashMap<>();
        bodyMap.put("phone",phone);
        bodyMap.put("code",code);

        System.out.println(rocketMQTemplate + "   ----");
        System.out.println(rocketMQTemplate.getProducer());
        System.out.println(rocketMQTemplate.getConsumer());

        // 发送消息（异步方式）
        rocketMQTemplate.convertAndSend("rocket-send1", bodyMap);

        return "验证码已发送";
    }

    @Override
    public void forgotPassword(long userId, String password) {

        //密码加密
        String newPassword = HashUtil.hashPassword(password);

        //重置密码
        UpdateWrapper<Passenger> wrapper=new UpdateWrapper<>();
        wrapper.eq("user_id",userId)
                .set("password",newPassword);

        userMapper.update(wrapper);
    }


    //校验手机格式
    private boolean isValidPhoneNumber(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }

    private boolean isRateLimited(String phone) {
        String key = "SMS_RATE_LIMIT:" + phone;
        String count = redisUtil.get(key);
        if (count == null) {
            redisUtil.set(key, "1");
            redisUtil.setExpire(key, 60); // 1分钟内限制
            return false;
        }
        int currentCount = Integer.parseInt(count);
        if (currentCount >= 3) { // 1分钟内最多发送3次
            return true;
        }
        redisUtil.set(key, String.valueOf(currentCount + 1));
        return false;
    }
}
